import 'dart:math';

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      // 启动要显示的界面
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  // 设置变量 _controller 并设置偏移量
  ScrollController _controller = ScrollController(initialScrollOffset: 200);
  /* 默认设置为 false */
  bool _isFloatingActionButton = false;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    _controller.addListener(() {
      print("监听到滚动");
      setState(() {
        _isFloatingActionButton = _controller.offset > 500 ? true : false;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("列表滚动测试"),
      ),
      body: ListView.builder(
          controller: _controller,
          itemCount: 20,
          itemBuilder: (BuildContext context, int index) {
            return ListTile(
              leading: Icon(Icons.people),
              title: Text("测试 $index"),
            );
          }
      ),
      floatingActionButton: _isFloatingActionButton ? FloatingActionButton(
        child: Icon(Icons.arrow_upward),
        onPressed: () {
          // 返回到顶部
          _controller.animateTo(0, duration: Duration(milliseconds: 200), curve: Curves.easeIn);
        },
      ) : null,
    );
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _controller.dispose();
  }
}



